package com.xcw.jac;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class JsonRequestExample {
    public static void main(String[] args) throws IOException {
        String url = "http://example.com/submit";  // JSON数据提交的URL

        // JSON数据
        String jsonData = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        // 将JSON数据转换为字节数组
        byte[] jsonDataBytes = jsonData.getBytes(StandardCharsets.UTF_8);

        // 创建连接
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Content-Length", String.valueOf(jsonDataBytes.length));
        conn.setDoOutput(true);

        // 发送请求
        try (OutputStream outputStream = conn.getOutputStream()) {
            outputStream.write(jsonDataBytes);
        }

        // 获取响应
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应内容
        } else {
            // 处理错误情况
        }

        conn.disconnect();
    }
}